package itbour.onetouchshow.activity.web;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.lsjr.callback.EncryBeanCallBack;
import com.lsjr.net.RequestParams;
import com.lsjr.utils.HttpUtils;
import com.three.pay.PayPlatform;
import com.three.pay.ThirdPayUtils;
import com.three.pay.bean.PayInfo;
import com.three.pay.listener.PayListener;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;

import itbour.onetouchshow.App;
import itbour.onetouchshow.activity.PaySuccessActivity;
import itbour.onetouchshow.base.BaseWebMvpActivity;
import itbour.onetouchshow.bean.JSCallBackBean;
import itbour.onetouchshow.bean.PayInfoBean;
import itbour.onetouchshow.constants.AppConfig;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.EncryptUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.ThirdAppInstall;
import itbour.onetouchshow.utils.UIUtils;

/**
 * Created by onetouch on 2017/12/1.
 */

@SuppressLint("ValidFragment")
public class CreateOrderActivity extends BaseWebMvpActivity {

    private final int DISMISS_DIALOG = 1;
    private final int SHOW_DIALOG = 2;
    private final String MSG_TAG = "message";
    public JSCallBackBean jsCallBackBean;
    private String docId;
    private int defaultPayType;
    private String itemId;
    private String priceId;
    private boolean isVipOrder;

    //    @SuppressLint("HandlerLeak")
//    private Handler handler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            super.handleMessage(msg);
//            if (msg.what==DISMISS_DIALOG){
//                dismissProgressDialog();
//            }
//            if (msg.what==SHOW_DIALOG){
//                if (msg.getData()!=null){
//                    Bundle bundle=msg.getData();
//                    String msg1 = bundle.getString(MSG_TAG);
//                    showProgressDialogWithText(msg1);
//                }else {
//                    showProgressDialogWithText("加载中...");
//                }
//            }
//        }
//    };
    private CommWebJsContrl commWebJsContrl;

    public static Intent getLaunchIntent(Context context, String itemId, String priceId, boolean isVipOrder) {
        Intent intent = new Intent(context, CreateOrderActivity.class);
        intent.putExtra(AppConst.ITEM_ID, itemId);
        intent.putExtra(AppConst.PRICE_ID, priceId);
        intent.putExtra(AppConst.IS_VIP_ORDER, isVipOrder);
        return intent;
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @Override
    protected void showTitle(String string) {

    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {

        itemId = getIntent().getStringExtra(AppConst.ITEM_ID);
        priceId = getIntent().getStringExtra(AppConst.PRICE_ID);
        isVipOrder = getIntent().getBooleanExtra(AppConst.IS_VIP_ORDER, false);
        commWebJsContrl = new CommWebJsContrl(this);
        commWebJsContrl.setPayPlatformListener(new CommWebJsContrl.PayPlatformListener() {
            @Override
            public void onPayWeiXin(PayInfoBean payInfoBean) {
                weiXinPay(payInfoBean);
            }

            @Override
            public void onPayZhifuBao(PayInfoBean payInfoBean) {
                aliPay(payInfoBean);
            }
        });
        if (!isVipOrder) {
            //正常订单
            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                docId = extras.getString("docId");
                defaultPayType = extras.getInt("defaultPayType");
            }
            if (TextUtils.isEmpty(docId)) {
                return;
            }

            //加密请求html页面
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            //设备来源于android端  请求html网页device用3
            stringStringHashMap.put("device", AppConst.ANDROID_DEVICE + "");
            stringStringHashMap.put("userId", App.getUserId() + "");//25
            stringStringHashMap.put("docId", docId);//32
            stringStringHashMap.put("payType", defaultPayType + "");//32
            L_.e("docId", docId + "userId:" + App.getUserId());
            RequestParams requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.GETPREWATERMARKORDERINFO_V1_0);
            String url = EncryptUtils.getPrintHtmlUrl(requestParams);
            L_.e(url);
            initAgentWeb(url);
            // mAgentWeb.getJsInterfaceHolder().addJavaObject(AppConst.CONTRL, new WebInteraction());
        } else {
            //Vip订单
            if (TextUtils.isEmpty(itemId)) {
                return;
            }
            //13260675856
            //加密请求html页面
            HashMap<String, String> stringStringHashMap = new HashMap<>();
            stringStringHashMap.put("device", AppConst.ANDROID_DEVICE + "");
            stringStringHashMap.put("userId", App.getUserId() + "");
            stringStringHashMap.put("itemId", itemId);
            stringStringHashMap.put("priceId", priceId + "");
            //stringStringHashMap.put("referralCode", "13260675856");

            RequestParams requestParams = EncryptUtils.transEncrytionWebViewParams(stringStringHashMap, AppConfig.GET_VIP_PAY_CREATR_ORDER_PAGE);
            String url = EncryptUtils.getPrintHtmlUrl(requestParams);
            initAgentWeb(url);
        }
        mAgentWeb.getJsInterfaceHolder().addJavaObject(AppConst.CONTRL, commWebJsContrl);
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("确认订单");
    }

    @Override
    protected void initView() {
        super.initView();
    }

    @Override
    public void finish() {
        super.finish();
    }


    public void onOrderPay(String orderId) {
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("device", AppConst.ANDROID_DEVICE);
        stringObjectHashMap.put("userId", App.getUserId());
        stringObjectHashMap.put("orderId", orderId + "");
        HttpUtils.getInstance().executeGet(AppConfig.GETORDERPAYPARAM_V1_0, stringObjectHashMap, new EncryBeanCallBack() {
            @Override
            protected void onXError(String exception) {
                L_.e(exception);
                //T_.showToastReal(exception);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        new OneToucDialog.Builder(CreateOrderActivity.this)
                                .content(exception).neutralText("确认").
                                onNeutral(new OneToucDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(OneToucDialog dialog, DialogAction which) {

                                    }
                                }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                                .show();
                    }
                });
                //handler.sendEmptyMessage(DISMISS_DIALOG);
            }

            @Override
            protected void onSuccess(String response) {
                // handler.sendEmptyMessage(DISMISS_DIALOG);
                PayInfoBean payInfoBean = new Gson().fromJson(response, PayInfoBean.class);
                if (payInfoBean.getPaymentPlatform() == 10) {
                    weiXinPay(payInfoBean);
                } else if (payInfoBean.getPaymentPlatform() == 20) {
                    aliPay(payInfoBean);
                }
            }
        });
    }


    public void aliPay(PayInfoBean payInfoBean) {
        PayInfo payInfo = new PayInfo();
        payInfo.setSign(payInfoBean.getAlipay().getOrderStr());
        ThirdPayUtils.initialize(CreateOrderActivity.this).pay(PayPlatform.AliPay, payInfo, new PayListener() {
            @Override
            public void paySuccess() {
                // T_.showToastReal("支付成功");
                // L_.e("支付成功");
                returnH5Success();
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(AppConst.IS_VIP_ORDER, isVipOrder);
                        openActivity(PaySuccessActivity.class, bundle);
                        L_.i("paySuccessfinish");
                        finish();

                    }
                }, 500);
            }

            @Override
            public void payFailure(Exception e) {
                // T_.showToastReal("支付失败");
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);
                // EventBus.getDefault().post(-999);
                returnH5Fail();
            }

            @Override
            public void userCancel() {
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);
                // EventBus.getDefault().post(-999);
                returnH5Fail();
            }
        });
    }

    public void weiXinPay(PayInfoBean payInfoBean) {
        if (!ThirdAppInstall.isWeixinAvilible(getApplicationContext())) {
            // handler.sendEmptyMessage(DISMISS_DIALOG);
            T_.showCustomToast("未安装微信或微信版本过低");
            returnH5Fail();
            return;
        }

        PayInfo payInfo = new PayInfo();
        payInfo.setNonceStr(payInfoBean.getWechat().getNonceStr());
        payInfo.setPrepayId(payInfoBean.getWechat().getPrepayId());
        payInfo.setTimeStamp(payInfoBean.getWechat().getTimeStamp());
        payInfo.setSign(payInfoBean.getWechat().getSign());
        ThirdPayUtils.initialize(CreateOrderActivity.this).pay(PayPlatform.WxPay, payInfo, new PayListener() {
            @Override
            public void paySuccess() {
                // T_.showToastReal("支付成功");
                // L_.e("支付成功");
                returnH5Success();
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Bundle bundle = new Bundle();
                        bundle.putBoolean(AppConst.IS_VIP_ORDER, isVipOrder);
                        openActivity(PaySuccessActivity.class, bundle);
                        L_.i("paySuccessfinish");
                        finish();

                    }
                }, 500);

            }

            @Override
            public void payFailure(Exception e) {
                // T_.showToastReal("支付失败");
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 500);
                // EventBus.getDefault().post(-999);
                returnH5Fail();
            }

            @Override
            public void userCancel() {
                //T_.showToastReal("支付失败");
                UIUtils.getHandler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showDialog();
                    }
                }, 100);
                // EventBus.getDefault().post(-999);
                returnH5Fail();

            }
        });
    }

    public void showDialog() {
        if (isFinishing()) return;
        new OneToucDialog.Builder(this)
                .content("支付未完成")
                .positiveText("重新支付").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                onOrderPay(jsCallBackBean.getOrderId() + "");
                //T_.showToastReal("重新支付");
            }
        })
                .negativeText("选择放弃").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                Log.e("TAH", "点击确定");
                //T_.showToastReal("选择放弃");
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();
    }


    public void returnH5Fail() {
        String fail = jsCallBackBean.getFail();
        if (!TextUtils.isEmpty(fail)) {
            String call = "javascript:" + fail + "()";
            getWebView().loadUrl(call);
        }

    }

    public void returnH5Success() {
        String success = jsCallBackBean.getSuccess();
        if (!TextUtils.isEmpty(success)) {
            String call = "javascript:" + success + "()";
            getWebView().loadUrl(call);
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("p5-确认订单"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this);          //统计时长
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("p5-确认订单"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }


}
